import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import vuexPersist  from "vuex-persist";
export default new Vuex.Store({
  state: {
    shopcar: [],
    num:0
  },
  mutations: {
    // 添加购物车
    add(state, item) {
      var flag = false;
      state.shopcar.forEach((i) => {
        if(i.id==item.id){
          flag=true
          i.num++
        }
      })
      if(!flag){
        item.num=1
        state.shopcar.push(item)
      }
    } ,  // 删除
    remove(state,id){
      state.shopcar.forEach((item,index)=>{
        if(item.id==id){
        state.shopcar.splice(index,1)
        }
      }) 
    },
    // 加
 plus(state,id){
   state.shopcar.forEach((item)=>{
     if(item.id==id){
       item.num++;
     }
   })
 },
//  减
 min(state,id){
  state.shopcar.forEach((item)=>{
    if(item.id==id){
      item.num--;
    }
  })
},
// 删除所选
del(state,ids){
  state.shopcar = state.shopcar.filter((item) => {
    if (ids.indexOf(item.id) == -1) {
      return item;
    }
  });
}
  },
  actions: {
  },
  modules: {
  },
  plugins: [
    new vuexPersist({
      storage: window.localStorage,
    }).plugin,
  ],
})